package com.ticket.sass.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ticket.sass.admin.dto.input.commodity.category.CommodityCategoryListInput;
import com.ticket.sass.admin.mapper.CommodityCategoryMapper;
import com.ticket.sass.admin.service.BaseService;
import com.ticket.sass.common.entity.tenant.CommodityCategoryEntity;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ywb
 * @since 2024-03-23
 */
@Service
public class CommodityCategoryServiceImpl extends ServiceImpl<CommodityCategoryMapper, CommodityCategoryEntity> implements BaseService<CommodityCategoryEntity> {
    /**
     * 获取有效的排序值
     * @param sort 排序值
     * @param id 记录ID，更新操作时使用
     * @return 返回计算后的排序值
     */
    public Integer getValidSort(Integer sort, Long id) {
        if (sort == null) {
            // 查询当前数据中最大的 sort
            Integer maxSort = getMaxSort();
            if (maxSort == null) {
                return 1;
            }
            return maxSort + 1;
        } else {
            // 检查 sort 是否在数据中存在
            boolean exists = isSortExists(sort, id);
            if (exists) {
                // 如果存在，则更新其他记录的 sort 值，使其自动加 1
                adjustSortValues(id, sort);
            }
            return sort;
        }
    }
    
    private Integer getMaxSort() {
        QueryWrapper<CommodityCategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("MAX(sort) as sort");
        CommodityCategoryEntity result = baseMapper.selectOne(queryWrapper);
        return result != null ? result.getSort() : null;
    }
    
    private boolean isSortExists(Integer sort, Long id) {
        QueryWrapper<CommodityCategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sort", sort);
        if (id != null) {
            queryWrapper.ne("id", id);
        }
        Long count = baseMapper.selectCount(queryWrapper);
        return count != null && count > 0;
    }
    
    private void adjustSortValues(Long id, Integer newSort) {
        CommodityCategoryEntity entity = baseMapper.selectById(id);
        if (entity == null) {
            return;
        }
        
        Integer oldSort = entity.getSort();
        if (oldSort == null || oldSort.equals(newSort)) {
            return;
        }
        
        UpdateWrapper<CommodityCategoryEntity> updateWrapper = new UpdateWrapper<>();
        if (oldSort < newSort) {
            updateWrapper.setSql("sort = sort - 1").gt("sort", oldSort).le("sort", newSort);
        } else {
            updateWrapper.setSql("sort = sort + 1").ge("sort", newSort).lt("sort", oldSort);
        }
        baseMapper.update(null, updateWrapper);
    }
    
    /**
     * 分页查询商品分类，默认根据 sort 排序
     * @param input 分页输入
     * @return 分页结果
     */
    public IPage<CommodityCategoryEntity> iPage(CommodityCategoryListInput input) {
        Page<CommodityCategoryEntity> page = new Page<>(input.getPageNum(), input.getPageSize());
        QueryWrapper<CommodityCategoryEntity> queryWrapper = new QueryWrapper<>();
        
        if (input.getName() != null && !input.getName().isEmpty()) {
            queryWrapper.like("name", input.getName());
        }
        
        queryWrapper.orderByAsc("sort");
        
        return this.page(page, queryWrapper);
    }
}
